package com.gxuwz.stats.service.excelhandler;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.event.AnalysisEventListener;
import com.gxuwz.stats.entity.AcademicPapers;
import com.gxuwz.stats.entity.AcademicWork;
import com.gxuwz.stats.entity.dto.AcademicPapersNewImportDTO;
import com.gxuwz.stats.service.SheetHandler;
import com.gxuwz.stats.service.SheetName;
import com.gxuwz.stats.service.excelNewHandler.AcademicPaperNewListener;
import com.gxuwz.stats.service.impl.AcademicPapersServiceImpl;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.List;

@Service
@SheetName("学术论文")
public class AcademicPapersHandler implements SheetHandler{
    @Autowired
    private AcademicPapersServiceImpl workloadService;

//    @Override
//    public void handle(Sheet sheet) {
//        // 将 Apache POI 的 Sheet 转换为 EasyExcel 的输入流（伪代码）
//        InputStream inputStream = convertSheetToInputStream(sheet);
//        String sheetName = sheet.getSheetName();
//        // 判断 sheetName 是否为空或为默认名（如 Sheet1），决定是否指定
//        if (sheetName != null && !sheetName.trim().isEmpty() && !sheetName.trim().toLowerCase().startsWith("sheet")) {
//            // 指定 sheet 名
//            EasyExcel.read(inputStream, AcademicPapers.class, new AcademicPaperListener(workloadService))
//                    .sheet(sheetName)
//                    .headRowNumber(1)
//                    .doRead();
//        } else {
//            // 不指定 sheet 名，默认第一个
//            EasyExcel.read(inputStream, AcademicPapers.class, new AcademicPaperListener(workloadService))
//                    .sheet()
//                    .headRowNumber(1)
//                    .doRead();
//        }
//        // 使用 EasyExcel 读取数据
////        EasyExcel.read(inputStream, AcademicPapers.class, new AcademicPaperListener(workloadService))
////                .sheet("学术论文")  // 指定 Sheet 名称
////                .headRowNumber(1) // 明确指定标题行
////                .doRead();
//    }

//    @Override
//    public List<String> getHeaderFields() {
//        // 这里写你的表头字段，和Excel第一行一致
//        return Arrays.asList("姓名", "成果名称", "期刊名称", "发表时间","ISSN号");
//    }

    private InputStream convertSheetToInputStream(Sheet sheet) {
        // 实现将 POI Sheet 转换为 InputStream 的逻辑（可能需要借助临时文件）
        // 此处仅为示例，实际需根据业务实现
        try {
            Workbook workbook = sheet.getWorkbook();
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            workbook.write(out);
            return new ByteArrayInputStream(out.toByteArray());
        } catch (IOException e) {
            throw new RuntimeException("Sheet转换输入流失败", e);
        }
    }


    @Override
    public ImportResultProvider handle(Sheet sheet, String username, String role, String department) {

        // 读取表头
        org.apache.poi.ss.usermodel.Row headerRow = sheet.getRow(0);
        if (headerRow == null) {
            throw new RuntimeException("Excel表格缺少表头，无法识别模板类型！");
        }
        java.util.List<String> headers = new java.util.ArrayList<>();
        for (org.apache.poi.ss.usermodel.Cell cell : headerRow) {
            headers.add(cell.getStringCellValue().trim());
        }

        // 判断模板类型
        boolean isOldTemplate = headers.contains("成果名称") && headers.contains("期刊名称");
        boolean isNewTemplate = headers.contains("论文名称") && headers.contains("发表刊物名称") && headers.contains("录入人");

        InputStream inputStream = convertSheetToInputStream(sheet);
        String sheetName = sheet.getSheetName();

        ImportResultProvider listener;

        if (isOldTemplate) {
            listener = new AcademicPaperListener(workloadService, username, role, department);
            if (sheetName != null && !sheetName.trim().isEmpty() && !sheetName.trim().toLowerCase().startsWith("sheet")) {
                EasyExcel.read(inputStream, AcademicPapers.class, (AnalysisEventListener<AcademicPapers>) listener)
                        .sheet(sheetName)
                        .headRowNumber(1)
                        .doRead();
            } else {
                EasyExcel.read(inputStream, AcademicPapers.class, (AnalysisEventListener<AcademicPapers>) listener)
                        .sheet()
                        .headRowNumber(1)
                        .doRead();
            }
        } else if (isNewTemplate) {
            listener = new AcademicPaperNewListener(workloadService, username, role, department);
            if (sheetName != null && !sheetName.trim().isEmpty() && !sheetName.trim().toLowerCase().startsWith("sheet")) {
                EasyExcel.read(inputStream, AcademicPapersNewImportDTO.class, (AnalysisEventListener<AcademicPapersNewImportDTO>) listener)
                        .sheet(sheetName)
                        .headRowNumber(1)
                        .doRead();
            } else {
                EasyExcel.read(inputStream, AcademicPapersNewImportDTO.class, (AnalysisEventListener<AcademicPapersNewImportDTO>) listener)
                        .sheet()
                        .headRowNumber(1)
                        .doRead();
            }
        } else {
            throw new RuntimeException("无法识别的学术论文导入模板，请检查表头！");
        }
        return listener;
    }
        //        InputStream inputStream = convertSheetToInputStream(sheet);
//        String sheetName = sheet.getSheetName();
//        AcademicPaperListener listener = new AcademicPaperListener(workloadService, username, role, department);
//        if (sheetName != null && !sheetName.trim().isEmpty() && !sheetName.trim().toLowerCase().startsWith("sheet")) {
//            EasyExcel.read(inputStream, AcademicPapers.class, listener)
//                    .sheet(sheetName)
//                    .headRowNumber(1)
//                    .doRead();
//        } else {
//            EasyExcel.read(inputStream, AcademicPapers.class, listener)
//                    .sheet()
//                    .headRowNumber(1)
//                    .doRead();
//        }
//        return listener;
//    }
}
